package com.xincongjun.media.classifier;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

import static com.xincongjun.media.utils.FileUtil.getRealFileType;

public class FileClassifier {

    private static final Logger logger = LoggerFactory.getLogger(FileClassifier.class);

    public static void organizeFilesType(String directoryPath){
        File dir = new File(directoryPath);
        if (!dir.exists() || !dir.isDirectory()) {
            logger.error("无效路径: ", directoryPath);
        }

        File[] files = dir.listFiles();
        if (files == null || files.length == 0) {
            logger.error("路径下不存在文件: ", directoryPath);
        }

        for (File file : files) {
            if (file.isFile()) {
                organizeFilesTypeProcessFile(file);
            }
        }

        logger.info("所有文件处理完成！");
    }

    private static void organizeFilesTypeProcessFile(File file) {
        String filePath = file.getAbsolutePath();
        String fileName = file.getName();

        try {
            String realExtension = getRealFileType(filePath);
            if (realExtension == null || realExtension.isEmpty()) {
                logger.error("无法识别的文件类型: {}", filePath);
                return;
            }

            File typeDir = new File(file.getParent(), realExtension);
            if (!typeDir.exists()) {
                if (!typeDir.mkdirs()) {
                    logger.error("创建文件夹失败: {}", typeDir.getAbsolutePath());
                    return;
                }
            }

            Path targetPath = Paths.get(typeDir.getAbsolutePath(), fileName);
            Files.move(file.toPath(), targetPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}
